<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表单验证</title>
    <script src="https://cdn.staticfile.org/vue/3.2.45/vue.global.js"></script>
</head>

<body>
    <div id="app">
        <form>
            <input type="text" v-model="inputData.address" placeholder="输入地址">
            <p v-if="!isAddress">格式错误 - 必须有【省】或【市】，必须有【州|县|城|区|村|镇|乡|湾|道|路|栋|幢|会|号|苑|巷|递|驿】其中一个</p>
            <br>
            <input type="text" v-model="inputData.name" placeholder="姓名">
            <p v-if="!isName">格式错误 - 必须为两字到六字中文</p>
            <br>
            <input type="tel" v-model.trime="inputData.phone" placeholder="电话">
            <p v-if="!isPhone">电话号码格式错误</p>
            <br>
            <button type="submit" @click="save">保存</button>
        </form>

    </div>
    <script>
        const App = Vue.createApp({
            setup() {
                //存储输入框信息
                const inputData = Vue.reactive({
                    address: "",
                    name: "",
                    phone: "",
                })
                //保存按钮
                const save = () => {
                    alert("点击咯")
                }
                //验证收件地址
                const isAddress = Vue.computed(() => {
                    // 正则表达式验证收件地址
                    //必须有省或市，必须有”县|区|村|镇|乡|湾“中的一个
                    const reg = /(省|市).*?(州|县|城|区|村|镇|乡|湾|道|路|栋|幢|会|号|苑|巷|递|驿)/

                    return reg.test(inputData.address)
                })
                //验证名称
                const isName = Vue.computed(() => {
                    // 正则表达式验证名字，2到6个中文字符
                    const reg = /^[\u4e00-\u9fa5]{2,6}$/
                    return reg.test(inputData.name)
                })
                //验证电话号码
                const isPhone = Vue.computed(() => {
                    // 正则表达式验证电话号码
                    const reg = /^1[3456789]\d{9}$/
                    return reg.test(inputData.phone)
                })
                Vue.watch(
                    () => inputData.phone,
                    (newVal, oldVal) => {
                        if (newVal !== oldVal) {
                            console.log("New phone:", newVal);
                            console.log("Validity:", isPhoneValid.value);
                        }
                    }
                );




                return {
                    inputData,
                    save,
                    isAddress,
                    isName,
                    isPhone,
                }
            }
        })
        App.mount("#app")



    </script>

</body>

</html>